import CryptoJS from "crypto-js";
class Encryption {
    constructor({ username, password }) {
        this.key = "s1d15bffb007d499";
        this.username = username;
        this.password = password;
    }

    /**
    * @method 获取加密后的值 encode
    * @param  { String } content   需要加密的字符串
    * @param  { String } keyStr  指定的key值
    * @return { String } 加密后的字符串
    */
    encode = (content, keyStr) => {
        //明文加密
        let options = {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7,
        };
        let varkey = CryptoJS.enc.Utf8.parse(keyStr);
        let encryptedData = CryptoJS.AES.encrypt(content, varkey, options);
        let encryptedBase64Str = encryptedData.toString();
        return encryptedBase64Str;
    }

    /**
    * @method 获取生成后的密钥 getKey
    * @param  { String } str   需要加密的字符串
    * @param  { String } key  指定的key值
    * @return { String } 加密后的字符串
    */
    getKey = (str, key) => {
        if (!key) key = this.key;
        if (str.length >= 16) {
            return str.substring(0, 16);
        }

        if (str.length < 16) {
            return str + key.substring(0, key.length - str.length);
        }
    }

    // 密码加密
    get = () => {
        const password = this.encode(
            this.password,
            this.getKey(this.username)
        );
        const username = this.encode(
            this.username,
            this.getKey(password.substring(0, 4))
        );
        return {
            username,
            password
        }
    };
}
export default Encryption;